package com.nexen.common.config.wechat;

import cn.binarywang.wx.miniapp.api.WxMaService;
import cn.binarywang.wx.miniapp.api.impl.WxMaServiceImpl;
import cn.binarywang.wx.miniapp.config.impl.WxMaDefaultConfigImpl;
import com.google.common.collect.Maps;
import me.chanjar.weixin.common.error.WxRuntimeException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Configuration;
import org.springframework.util.CollectionUtils;

import javax.annotation.PostConstruct;
import java.util.List;
import java.util.Map;

/**
 * <p>Title: WxMaConfiguration</p>
 * <p>Description: </p>
 *
 * @author cong.zhang
 * @date 2024/8/5
 * @time 3:27
 * @version 1.0.0
 */
@Configuration
@EnableConfigurationProperties(WxMaProperties.class)
public class WxMaConfiguration {

    @Autowired
    WxMaProperties properties;

    public static final Map<String, WxMaService> serviceList = Maps.newHashMap();

    public static WxMaService getService(String appId) {
        if (serviceList.containsKey(appId)) {
            return serviceList.get(appId);
        }
        throw new RuntimeException("appId不存在");
    }

    @PostConstruct
    public void init() {
        List<WxMaProperties.Config> configs = this.properties.getConfigs();
        if (CollectionUtils.isEmpty(configs)) {
            throw new WxRuntimeException("请添加wx.miniapp 小程序信息配置！");
        }

        for (WxMaProperties.Config cfg : configs) {
            WxMaService maService = new WxMaServiceImpl();
            WxMaDefaultConfigImpl config = new WxMaDefaultConfigImpl();
            config.setAppid(cfg.getAppid());
            config.setSecret(cfg.getSecret());
            config.setToken(cfg.getToken());
            config.setAesKey(cfg.getAesKey());
            config.setMsgDataFormat(cfg.getMsgDataFormat());
            maService.setWxMaConfig(config);
            serviceList.put(cfg.getAppid(), maService);
        }
    }
}